package com.study.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class MyFilter1 extends ZuulFilter {

    /**
     * 设置过滤器类型: pre/post/route/error
     *  pre: 前置, post: 后置
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 设置优先级, 值越大优先级越低
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 当前过滤器是否生效, true: 生效; false: 不生效
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器执行的内容
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            // 不放行
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            // 给客户端提示
            try {
                context.getResponse().getWriter().println("token error");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
